package com.example.cinema.request;

import android.util.Log;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.BufferedSource;
import okio.ForwardingSink;
import okio.ForwardingSource;
import okio.Okio;
import okio.Source;

/**
 * 上传进度 请求体改造
 */
public class ProgressResponseBody extends RequestBody {
    private RequestBody mRequestBody;//请求体
    private int mCurrentLength;//当前长度
    private ProgressResponseListener responseListener;//进度监听接口
    public ProgressResponseBody(MultipartBody multipartBody)
    {//构造方法 多部分请求体MultipartBody 赋给 请求体
        this.mRequestBody = multipartBody;
    }
    public ProgressResponseBody(MultipartBody multipartBody,ProgressResponseListener listener)
    {
        this.mRequestBody = multipartBody;
        this.responseListener = listener;
    }

    @Nullable
    @Override//内容类型
    public MediaType contentType() {//媒体类型
        return mRequestBody.contentType();
    }

    @Override
    public long contentLength() throws IOException {//内容长度
        return  mRequestBody.contentLength();
    }

    @Override //写入接口
    public void writeTo(@NotNull BufferedSink bufferedSink) throws IOException {
        Log.i("TTT","监听");
       final long total = contentLength();//发送的数据总长度
        //转发链接用于获取写入数据长度
        ForwardingSink forwardingSink = new ForwardingSink(bufferedSink){
            @Override//写入接口 source 是发送缓存  byetCount是好的直接长度
            public void write(@NotNull Buffer source, long byteCount) throws IOException {
                mCurrentLength += byteCount;
                Log.i("TTT",total+"==="+mCurrentLength);
                if(responseListener != null || total == mCurrentLength){
                    responseListener.onResponseProgress(mCurrentLength,total,false);
                }
                super.write(source, byteCount);
            }
        };
        //Okio的buffer 从转发链接中读取缓存到 缓存器BufferedSink
        BufferedSink bufferedSink1 = Okio.buffer(forwardingSink);
        //将缓存器中的内容写入到 请求体中
        mRequestBody.writeTo(bufferedSink1);
        //刷新缓存
        bufferedSink1.flush();
    }

}